package sf.database.jdbc.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

public class BooleanCharType implements TypeHandler<Boolean> {
    public Boolean get(ResultSet rs, String colName) throws SQLException {
        String s = rs.getString(colName);
        return changeBoolean(s);
    }

    public Boolean get(ResultSet rs, int index) throws SQLException {
        String s = rs.getString(index);
        return changeBoolean(s);
    }

    public Boolean get(CallableStatement cs, int index) throws SQLException {
        String s = cs.getString(index);
        return changeBoolean(s);
    }

    @Override
    public Boolean get(CallableStatement cs, String parameterName) throws SQLException {
        String s = cs.getString(parameterName);
        return changeBoolean(s);
    }

    private Boolean changeBoolean(String s) {
        if (s != null && s.length() > 0) {
            char c = s.charAt(0);
            return c == '1' || c == 'T' || c == 't';
        }
        return null;
    }

    public Object set(PreparedStatement stat, Object obj, int i) throws SQLException {
        if (obj == null) {
            stat.setNull(i, java.sql.Types.CHAR);
            return null;
        } else {
            String str = ((Boolean) obj) ? "1" : "0";
            stat.setString(i, str);
            return str;
        }
    }

    @Override
    public Object set(CallableStatement cs, Object obj, String parameterName) throws SQLException {
        if (obj == null) {
            cs.setNull(parameterName, java.sql.Types.CHAR);
            return null;
        } else {
            String str = ((Boolean) obj) ? "1" : "0";
            cs.setString(parameterName, str);
            return str;
        }
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        String str = ((Boolean) value) ? "1" : "0";
        rs.updateString(columnLabel, str);
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        String str = ((Boolean) value) ? "1" : "0";
        rs.updateString(columnIndex, str);
    }

    @Override
    public int getSqlType() {
        return Types.CHAR;
    }

    @Override
    public Class<Boolean> getDefaultJavaType() {
        return Boolean.class;
    }

}
